import 'dart:convert';
import 'dart:math';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:leader_doctor_flutter/common/data/app.dart';
import 'package:leader_doctor_flutter/common/http/api.dart';
import 'package:leader_doctor_flutter/common/http/http_client.dart';
import 'package:leader_doctor_flutter/common/utils/image_utils.dart';
import 'package:leader_doctor_flutter/common/widget/comm_widget.dart';
import 'package:leader_doctor_flutter/common/widget/refresh_custom_widget.dart';
import 'package:leader_doctor_flutter/common/widget/table_placeholder_widget.dart';
import 'package:leader_doctor_flutter/model/my_gift_comment_list.dart';
import 'package:leader_doctor_flutter/model/my_gift_number.dart';
import 'package:leader_doctor_flutter/styles/colors.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

class MyGiftPage extends StatefulWidget {
  const MyGiftPage({super.key});

  @override
  State<MyGiftPage> createState() => _MyGiftPageState();
}

class _MyGiftPageState extends State<MyGiftPage> {
  var pageSize = 20;
  var pageNo = 1;
  String count = "0";
  bool dataLoaded = false; // 数据请求中

  final RefreshController _refreshController = RefreshController(initialRefresh: false);

  void _onRefresh() async {
    pageNo = 1;
    _getGiftCommentList();
    _refreshController.refreshCompleted();
  }

  void _onLoading() async {
    pageNo++;
    _getGiftCommentList();
    _refreshController.loadComplete();
  }

  @override
  void initState() {
    super.initState();
    _initializeData();
  }

  _initializeData() async {
    await _getAllMyGift();
    await _getGiftCommentList();
  }

  @override
  void dispose() {
    _refreshController.dispose();
    super.dispose();
  }

  List<MyGiftModel> giftItems = [];
  List<MyGiftCommentListModel> giftCells = [];

  @override
  Widget build(BuildContext context) {
    return contentView();
  }

  Widget contentView() {
    return Scaffold(
      appBar: CommWidget.getCommAppbar(context),
      body: Container(
        color: ColorRes.white,
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            SizedBox(
              height: 10.w,
              child: Container(color: Color(0xFFF5F5F5)),
            ),
            Container(
                width: double.infinity,
                color: Color(0xFFFFFFFF),
                padding: EdgeInsets.only(left: 12.w, right: 12.w, top: 15.w),
                child: Text(
                  "共收到的礼物：",
                  style: TextStyle(fontSize: 16.sp, fontWeight: FontWeight.w500),
                )),
            Container(
              margin: EdgeInsets.only(top: 15.w, bottom: 15.w),
              color: ColorRes.white,
              child: GridView.builder(
                padding: EdgeInsets.zero,
                gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
                  crossAxisCount: 4,
                  crossAxisSpacing: 15.0,
                  mainAxisSpacing: 0.0,
                ),
                shrinkWrap: true,
                physics: const NeverScrollableScrollPhysics(),
                itemCount: giftItems.length,
                itemBuilder: (context, index) {
                  return GiftCell(giftItems[index]);
                },
              ),
            ),
            SizedBox(
              height: 10.w,
              child: Container(color: Color(0xFFF5F5F5)),
            ),
            Container(
                color: Color(0xFFFFFFFF),
                width: double.infinity,
                padding: EdgeInsets.only(left: 12.w, right: 12.w, bottom: 8.w, top: 10.w),
                child: Text(
                  "评论(共${count}个)",
                  style: TextStyle(fontSize: 16.sp, fontWeight: FontWeight.w500),
                )),
            Expanded(
              child: Container(
                color: Colors.white,
                child: SmartRefresher(
                    controller: _refreshController,
                    enablePullDown: true,
                    enablePullUp: true,
                    onRefresh: _onRefresh,
                    onLoading: _onLoading,
                    child: dataLoaded
                        ? (giftCells.isEmpty
                            ? TablePlaceholderWidget(
                                message: "暂无数据",
                                yOffset: -30,
                              )
                            : ListView.separated(
                                itemBuilder: (context, index) {
                                  return GiftListCell(giftCells[index]);
                                },
                                separatorBuilder: (context, index) {
                                  return Container(
                                    margin: EdgeInsets.only(left: 12.w, right: 12.w),
                                    child: Divider(height: 1.w, color: Color(0xFFE1E1E1)),
                                  );
                                },
                                itemCount: giftCells.length,
                              ))
                        : Container()),
              ),
            ),
          ],
        ),
      ),
    );
  }

  /// 获取顶部礼物类型
  _getAllMyGift() async {
    var user = App.instance.userInfo;
    var httpRequest = HttpRequest(Api.getAllGift, body: {
      'medicalId': user?.id,
    });
    var httpResponse = await HttpClient.postJson(httpRequest);
    var map = jsonDecode(utf8.decode(httpResponse.raw!.bodyBytes));
    print("共收到的礼物：${map}, userId = ${user?.id}");
    var tmpList = ((map['responseBody'] as List?) ?? []).map((e) => MyGiftModel.fromJson(e)).toList();
    giftItems.addAll(tmpList);
    setState(() {});
  }

  /// 获取礼物评论
  _getGiftCommentList() async {
    var user = App.instance.userInfo;
    var httpRequest = HttpRequest(Api.getGiftCommenList,
        urlParams: {'medicalUserId': user?.id, "pageIndex": pageNo.toString(), "pageSize": pageSize.toString()});
    var httpResponse = await HttpClient.post(httpRequest);
    var map = jsonDecode(utf8.decode(httpResponse.raw!.bodyBytes));
    count = map['count'].toString();
    print("评论数量：${map}, userId = ${user?.id}");
    var tmpList = ((map['responseBody'] as List?) ?? []).map((e) => MyGiftCommentListModel.fromJson(e)).toList();
    if (tmpList.length < pageSize) {
      _refreshController.loadNoData();
    } else {
      _refreshController.loadComplete();
    }
    pageNo == 1 ? giftCells = tmpList : giftCells.addAll(tmpList);
    setState(() {
      dataLoaded = true;
    });
  }
}

// 顶部礼物
class GiftCell extends StatelessWidget {
  final MyGiftModel giftModel;

  GiftCell(this.giftModel);

  @override
  Widget build(BuildContext context) {
    String? name = "${giftModel.amount}${giftModel.unit}${giftModel.name}";

    return Container(
      // color: Colors.amber,
      child: Center(
        child: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              ImageLoader.loadImage(
                giftModel.iconUrl ?? '',
                size: Size(50.w, 50.w),
                fit: BoxFit.contain,
              ),
              SizedBox(height: 13.w),
              Text(
                name,
                style: TextStyle(fontSize: 13.sp, color: Color(0XFF666666)),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

// 评论列表
class GiftListCell extends StatelessWidget {
  final MyGiftCommentListModel listModel;

  GiftListCell(this.listModel);

  @override
  Widget build(BuildContext context) {
    String? title = "${listModel.patientName} 送给你${listModel.giftAmount}${listModel.giftUnit}${listModel.giftName}";

    return Column(
      children: [
        Padding(
          padding: EdgeInsets.only(left: 15.w, right: 12.w, bottom: 10.0.w, top: 10.w),
          child: Row(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              CircleAvatar(
                backgroundImage: NetworkImage(listModel.patientIcon ?? ''),
                radius: 20,
              ),
              SizedBox(width: 12.w),
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Row(
                      crossAxisAlignment: CrossAxisAlignment.end,
                      children: [
                        Container(
                          child: Text(
                            title,
                            style: TextStyle(fontSize: 15.sp, fontWeight: FontWeight.bold, color: Color(0xFF353535)),
                          ),
                        ),
                        SizedBox(width: 12.0.w), // 间距
                        Container(
                          child: Text(
                            listModel.createTime ?? '',
                            style: TextStyle(fontSize: 12.sp, fontWeight: FontWeight.normal, color: Color(0xFF999999)),
                          ),
                        ),
                      ],
                    ),
                    SizedBox(height: 5.0.w),
                    Container(
                      child: Text(listModel.evaluate ?? '',
                          style: TextStyle(fontSize: 14.sp, fontWeight: FontWeight.normal, color: Color(0xFF666666))),
                    ),
                  ],
                ),
              ),
            ],
          ),
        ),
      ],
    );
  }
}
